package top.songxs.base;

import com.github.pagehelper.util.StringUtil;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

public abstract class BaseController {

    /**
     * 封装页面提交的分页参数及搜索条件
     * @param request
     * @return
     *  // http://localhost:8000/role?roleName=张三&roleCode=System&hobby=music&hobby=sports&pageNum=2&pageSize=5
     * // http://localhost:8000/role?roleName=张三&roleCode=System
     * // http://localhost:8000/role
     */

    //封装通用方法，将成功的信息放入请求域中
    private static final String PAGE_SUCCESS = "common/successPage";
    public String successPage(Model model, String successMessage){
        //1.将成功信息放入请求域
        model.addAttribute("messagePage",successMessage);
        //2.显示成功页面
        return PAGE_SUCCESS;
    }

    protected Map<String, Object> getFilters(HttpServletRequest request) {
        Enumeration<String> paramNames = request.getParameterNames(); // [roleName,roleCode,hobby,pageNum,pageSize]
        /*
            key          value
            roleName     张三
            roleCode     System
            hobby       [music,sports]
            pageNum     2
            pageSize   5
         */
        Map<String, Object> filters = new TreeMap();
        while(paramNames != null && paramNames.hasMoreElements()) {
            String paramName = (String)paramNames.nextElement(); //roleName  roleCode  hobby  pageNum  pageSize
            String[] values = request.getParameterValues(paramName);//[张三]  [System]  [music,sports] [2]  [5]
            if (values != null && values.length != 0) {
                if (values.length > 1) {
                    filters.put(paramName, values);
                } else {
                    filters.put(paramName, values[0]);
                }
            }
        }
        if(!filters.containsKey("pageNum")) {
            filters.put("pageNum", 1);
        }
        if(!filters.containsKey("pageSize")) {
            filters.put("pageSize", 5);
        }

        return filters;
    }
}
